package com.taoye.thread;

import cn.hutool.core.date.DateUtil;

/**
 * @author Administrator
 */
public class Demo28 {
    public static void main(String[] args) throws InterruptedException {
        Demo28Service service = new Demo28Service();
        Thread t = new Demo28ThreadA(service);
        t.setName("A");
        t.start();
        Thread t1 = new Demo28ThreadA(service);
        t1.setName("B");
        t1.start();
        Thread t2 = new Demo28ThreadB(service);
        t2.setName("C");
        t2.start();
        Thread t3 = new Demo28ThreadB(service);
        t3.setName("D");
        t3.start();
        Thread.sleep(8000);
    }
}

class Demo28Service {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    /**
     * 这里是模拟业务逻辑1
     */
    public void fun1() {
        synchronized (lock1) {
            try {
                System.out.println(Thread.currentThread().getName() + "线程执行了fun1，当前时间：" + DateUtil.now());
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + "线程fun1执行结束，当前时间：" + DateUtil.now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 这里是模拟业务逻辑2
     */
    public void fun2() {
        synchronized (lock2) {
            try {
                System.out.println(Thread.currentThread().getName() + "线程执行了fun2，当前时间：" + DateUtil.now());
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + "线程fun2执行结束，当前时间：" + DateUtil.now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Demo28ThreadA extends Thread {
    private Demo28Service service;

    public Demo28ThreadA(Demo28Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.fun1();
    }
}

class Demo28ThreadB extends Thread {
    private Demo28Service service;

    public Demo28ThreadB(Demo28Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.fun2();
    }
}
